package com.niuwa.p2p.service.impl.protocol;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.mvc.entity.JsonResult;
import com.niuwa.p2p.core.mvc.entity.PageBean;
import com.niuwa.p2p.core.utils.DictConstant;
import com.niuwa.p2p.core.utils.StringUtil;
import com.niuwa.p2p.dao.nwfile.NWFileDao;
import com.niuwa.p2p.dao.protocol.ProtocolDao;
import com.niuwa.p2p.entity.PageQuery;
import com.niuwa.p2p.entity.nwfile.NWFile;
import com.niuwa.p2p.entity.productTemplate.ProductProtocol;
import com.niuwa.p2p.entity.productTemplate.ProtocolFile;
import com.niuwa.p2p.exception.BusinessException;
import com.niuwa.p2p.service.protocol.IProtocolService;
import com.niuwa.p2p.service.sequence.ISequenceService;
import com.niuwa.p2p.vo.protocol.ProductProtocolVo;

/**
 * 协议接口
 * @author lijian
 */
@Service
public class ProtocolServiceImpl implements IProtocolService {

	@Autowired
	private ProtocolDao protocolDao;
	
	@Autowired
	private ISequenceService sequenceService;
	
	@Autowired
	private NWFileDao nwFileDao;
	
	/**
	 * 查询符合条件的协议
	 */
	@Override
	public PageBean<ProductProtocolVo> selectProtocolBySelective(Map<String, Object> paramMap) {
		assert paramMap.get(PageQuery.PAGEQUERY) != null;
		//创建时间区间
		String startDate = (String) paramMap.get("startDate");
		if (StringUtils.isNotBlank(startDate))
			paramMap.put("startDate", startDate.concat(" 00:00:00"));
		String endDate = (String) paramMap.get("endDate");
		if (StringUtils.isNotBlank(endDate))
			paramMap.put("endDate", endDate.concat(" 23:59:59"));
		//添加未删除判断
		paramMap.put("delFlag", DictConstant.FlagStatus.N);//显示
		int totalCount = protocolDao.selectProtocolCountBySelective(paramMap);
		PageBean<ProductProtocolVo> page = new PageBean<ProductProtocolVo>(totalCount);
		page.setPage(((PageQuery) paramMap.get(PageQuery.PAGEQUERY)).getPage());
		page.setRows(protocolDao.selectProtocolBySelective(paramMap));
		return page;
	}

	@Override
	public JsonResult deleteProtocolBySelective(Long protId,Long operator) {
		JsonResult jsonResult=new JsonResult(false,"删除异常!");
		try {
			if (protId!=null && StringUtils.isNotBlank(String.valueOf(protId))
					&& operator!=null && StringUtils.isNotBlank(String.valueOf(operator))) {
				//先判断当前操作协议的状态(待审核、未通过两种状态下，协议可删除)
				ProductProtocolVo protocol=protocolDao.getProtocolByProtId(protId);
				if (protocol!=null && (protocol.getProtStatus().equals(DictConstant.ProtStatus.WAIT.getCode())
						|| protocol.getProtStatus().equals(DictConstant.ProtStatus.NO_PASS.getCode()))) {
					Map<String, Object> paramMap =new HashMap<String, Object>();
					paramMap.put("protId",protId);
					paramMap.put("operator",operator);
					paramMap.put("delFlag", DictConstant.FlagStatus.Y);//不显示
					Object obj = protocolDao.deleteProtocolBySelective(paramMap);
					if (Integer.parseInt(obj.toString())>0) {
						jsonResult=new JsonResult(true,"删除成功!");
					}else{
						jsonResult.setMsg("删除失败!");
					}
				}else{
					jsonResult=new JsonResult(false,"该信息不能删除，请刷新重试!");
				}
			}else{
				jsonResult=new JsonResult(false,"参数异常!");
			}
		} catch (Exception e) {
			// TODO: LOG
			e.printStackTrace();
		}
		return jsonResult;
	}
	
	@Override
	public List<ProductProtocolVo> selectAllProtocol() {
		List<ProductProtocolVo> list = new ArrayList<ProductProtocolVo>();
		try {
			list = protocolDao.getAllProtocol();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<ProductProtocolVo> selectProtocolVersionByName(String protName) {
		 List<ProductProtocolVo> list = new ArrayList<ProductProtocolVo>();
		 try {
			 list = protocolDao.getProtocolVersionByName(protName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		 return list;
	}

	@Override
	public ProductProtocolVo selectProtocolByNameAndVersion(ProductProtocolVo protocolVo) {
		try {
			ProductProtocolVo protocol = protocolDao.getProtocolByNameAndVersion(protocolVo);
			return protocol;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 添加 产品协议信息
	 * 
	 * @param productProtocol 产品协议信息
	 * @return 更新条数
	 * @throws 添加失败
	 *            
	 */
	@Override
	public int addProductProtocol(ProductProtocol productProtocol, List<String> protFileID, long operator) throws Exception {
		//产品类型
		String protType = productProtocol.getProtType();
		String protCode = "";
		//根据产品类型,取得产品编码
		for(DictConstant.ProtType e : DictConstant.ProtType.values()) {
			if(e.getCode().equals(protType)) {
				// 产品编码
				protCode = sequenceService.getCompleteSequenceBySeqKey(e.getSeqKey());
	         }
	    }
		//String protCode = getProtocolSeq(productProtocol.getProtType());
		if(StringUtil.isEmpty(protCode)){
			throw new BusinessException("protocolServiceImpl.failTOgetProductProtocolSeq");
		}
		productProtocol.setProtCode(protCode);
		productProtocol.setProtStatus(DictConstant.ProtStatus.WAIT.getCode());
		productProtocol.setOperator(operator);
		
		// check 协议版本是否已经存在
		ProductProtocol p = protocolDao.selectProductProtocolLastVersionByProtName(productProtocol.getProtName());
		if(p != null){
			if(productProtocol.getMainVersion() < p.getMainVersion()) {
				throw new BusinessException("protocolServiceImpl.mainVersionIsExist", 
						new String[]{p.getProtName(), p.getMainVersion() + "." + p.getMinorVersion()});
			} else if(productProtocol.getMinorVersion() <=p.getMinorVersion()) {
				throw new BusinessException("protocolServiceImpl.minVersionIsExist", 
						new String[]{p.getProtName(), p.getMainVersion() + "." + p.getMinorVersion()});
			}else if(productProtocol.getMainVersion() == p.getMainVersion() && productProtocol.getMinorVersion() == p.getMinorVersion()) {
				throw new BusinessException("protocolServiceImpl.versionIsExist", 
						new String[]{p.getProtName(), p.getMainVersion() + "." + p.getMinorVersion()});
			}
		}
		
		// 添加协议
		int result = protocolDao.insertProductProtocol(productProtocol);
		if (result != 1) {
			throw new BusinessException("protocolServiceImpl.failTOAddProductProtocol");
		}
		// 添加协议关联文件
		for(String fileId : protFileID) {
			ProtocolFile protocolFile = new ProtocolFile();
			protocolFile.setProtId(productProtocol.getId());
			protocolFile.setFileId(fileId);
			result = protocolDao.insertProtocolFile(protocolFile);
			if (result != 1) {
				throw new BusinessException("protocolServiceImpl.failTOAddProtocolFile");
			}
		}
		return result;
	}

	/**
	 * 根据产品类型,取得产品编码
	 * 
	 * @param protType 产品类型
	 * @return 产品编码
	 * @throws Exception           
	 */
	/*private String getProtocolSeq(String protType) throws Exception{
       for(DictConstant.ProtType e : DictConstant.ProtType.values()) {
            if(e.getCode().equals(protType)) {
            	return e.getSeqKey()+sequenceService.getNextSequenceBySeqKey(e.getSeqKey());
            }
        }
       return "";
	}*/
	
	/**
	 *  取得所有产品协议名称
	 * 
	 * @return  取得所有产品协议名称
	 * @throws 添加失败
	 *            
	 */
	@Override
	public List<String> selectAllProtName() {
		List<String>  result = protocolDao.selectAllProtName();
		if(result.size() == 0) {
			throw new BusinessException("protocolServiceImpl.failTOGetProductProtocolPortName");
		}
		return result;
	
	}

	/**
	 * 获取协议相关附件
	 */
	@Override
	public List<NWFile> selectProtFilesByProtId(long protId) {
		List<NWFile> protFiles=null;
		try {
			protFiles=nwFileDao.selectProtFilesByProtId(protId);
		} catch (Exception e) {
			//TODO LOG
			e.printStackTrace();
		}
		return protFiles;
	}

	@Override
	public ProductProtocolVo getProtocolByProtId(long protId) {
		return protocolDao.getProtocolByProtId(protId);
	}

	@Override
	public List<ProductProtocolVo> getProtocolByType(String protType) {
		List<ProductProtocolVo> list=null;
		try {
			list=protocolDao.getProtocolByType(protType);
		} catch (Exception e) {
			//TODO LOG
			e.printStackTrace();
		}
		return list;
	}

}
